
% Compute the OLS coefficient estimators (b), estimator for assymptotic
% variance (Vb) and standard erros of the coefficients (sb).
% X regressors matrix, y dependent variable
% NaN treated as missing values


function [b,Vb,sb,keepX,ssr] = ols(y,X,varagin)


% Treat NaN as missing values:

D = sum(isnan([y X]),2);
D = (D==0);
D = logical(D);
y = y(D);
X = X(D,:);


n = size(y,1);

% Check for colinearities:
[b]=regress(y,X);
dropped = logical(b(:)==0);
keepX   = logical(1-dropped);
X = X(:,keepX);



%% OLS
Q = X'*X;
b = Q\(X'*y); % OLS estimated coefficient
y_hat = X*b; % predicted value
e_hat = y - y_hat; % residual
ssr = e_hat'*e_hat;

%% Vb - b_hat variance estimator
D = zeros(size(size(X,2)));

for i=1:n
    d = X(i,:)'*X(i,:)*e_hat(i)^2;
    D = D + d;
end

Vb = n*(Q\D/Q); % Variance matrix

sb = n^(-.5)*sqrt(diag(Vb)); % Standard errors for beta


% Display results


if nargin>2
    disp([varagin' num2cell(b) num2cell(sb) num2cell(b./sb)])
    disp('---')
    fprintf(1,'%4s','N'); fprintf(1,'%6.0f',size(y,1)); fprintf(1,'\n');
end



